#include "widget.h"
#include<QpaintEvent>
#include<QPainter>//绘图的
#include<QPixmap>//来保存图片
#include<QCursor>
#include<QMetaEnum>
Widget::Widget(QWidget *parent)
    : QWidget(parent),
    timer(new QTimer(this)),
    menu(new QMenu(this))
{
    this->setWindowFlag(Qt::FramelessWindowHint);//去除边框
    this->setAttribute(Qt::WA_TranslucentBackground);//背景透明
    this->installEventFilter(new DragFilter);//捕捉鼠标运行
    connect(timer,&QTimer::timeout,[this](){
        static int index=0;//记录当前图片
        auto paths=  this->action_map.value(this->cur_role_act);//得到路径位置
        this->cur_role_pix=paths[index++%paths.size()];
        this->update();//到时间重新绘制，实现图片切换

    });
    initMenu();
    loadRoleActRes();//加载图片
    showActAnimation(RoleAct::sad);//显示图片

}

Widget::~Widget() {}

void Widget::showActAnimation(RoleAct k)
{ timer->stop();
    this->cur_role_act=k;
    timer->start(50);//每隔50ms切换
}

void Widget::onMenuTriggered(QAction *action)
{
    QMetaEnum a=QMetaEnum::fromType<RoleAct>();
    bool T;
   int k= a.keysToValue(action->text().toStdString().c_str(),&T);
    if(!T){return ;}

    showActAnimation(static_cast<RoleAct>(k));

}


void Widget::paintEvent(QPaintEvent *event)
{

    QPainter painter(this);

    QPixmap pix;
    pix.load(this->cur_role_pix.toLocalFile());//加载图片
    painter.drawPixmap(0,0,pix);
}//完成绘制

void Widget::contextMenuEvent(QContextMenuEvent *event)
{
    this->menu->popup(QCursor::pos());
}

void Widget::loadRoleActRes()
{
    auto addRes=[this](RoleAct k,QString path,int count){
        QList<QUrl>paths;
        char buf[260];
        for(int i=0;i<count;++i){
            memset(buf,0,sizeof(buf));
            sprintf_s(buf,path.toStdString().c_str(),i);
            paths.append(QUrl::fromLocalFile(buf));
        }
        action_map.insert(k,paths);
    };
    addRes(RoleAct::sad,":/sad/img/sad/%d.png",41);
    addRes(RoleAct::uhhuh,":/uh-huh/img/uh-huh/%d.jpg",44);
    addRes(RoleAct::writing,":/writing/img/writing/%d.jpg",46);
}

void Widget::initMenu()
{
    menu->addAction("sad");
    menu->addAction("uh-huh");
    menu->addAction("writing");
    QAction* act=new QAction("隐藏");
    connect(act,&QAction::triggered,[this](){
        this->setVisible(false);//设置窗口不可见
    });
    menu->addAction(act);
    connect(this->menu,&QMenu::triggered,this,&Widget::onMenuTriggered);
}//添加菜单
